package com.yida.gwj.scene.expend.service.impl;

import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yida.common.core.exception.ServiceException;
import com.yida.common.core.utils.DateUtils;
import com.yida.common.core.utils.StringUtils;
import com.yida.common.security.utils.SecurityUtils;
import com.yida.gwj.common.domain.GwjBaseHouse;
import com.yida.gwj.scene.expend.domain.GwjSceneExpendBusinessHouse;
import com.yida.gwj.scene.expend.domain.GwjSceneExpendBusinessHouseAndOwner;
import com.yida.gwj.scene.expend.domain.GwjSceneExpendBusinessOwner;
import com.yida.gwj.scene.expend.domain.request.GwjSceneExpendHouseAndOwnerRequest;
import com.yida.gwj.scene.expend.mapper.GwjSceneExpendBusinessHouseMapper;
import com.yida.gwj.scene.expend.service.IGwjSceneExpendBusinessHouseService;
import com.yida.gwj.scene.expend.service.IGwjSceneExpendBusinessOwnerService;
import com.yida.system.api.domain.SysUser;

/**
 * 业务房屋信息（旧支出模块）Service业务层处理
 * 
 * @author hmh
 * @date 2023-08-14
 */
@Service
public class GwjSceneExpendBusinessHouseServiceImpl implements IGwjSceneExpendBusinessHouseService {
    @Autowired
    private GwjSceneExpendBusinessHouseMapper gwjSceneExpendBusinessHouseMapper;
    @Autowired
    private IGwjSceneExpendBusinessOwnerService iGwjSceneExpendBusinessOwnerService;

    /**
     * 查询业务房屋信息（旧支出模块）
     * 
     * @param bizHouseId 业务房屋信息（旧支出模块）主键
     * @return 业务房屋信息（旧支出模块）
     */
    @Override
    public GwjSceneExpendBusinessHouse selectGwjSceneExpendBusinessHouseByBizHouseId(Long bizHouseId) {
        return gwjSceneExpendBusinessHouseMapper.selectGwjSceneExpendBusinessHouseByBizHouseId(bizHouseId);
    }

    /**
     * 查询业务房屋信息（旧支出模块）列表
     * 
     * @param gwjSceneExpendBusinessHouse 业务房屋信息（旧支出模块）
     * @return 业务房屋信息（旧支出模块）
     */
    @Override
    public List<GwjSceneExpendBusinessHouse> selectGwjSceneExpendBusinessHouseList(GwjSceneExpendBusinessHouse gwjSceneExpendBusinessHouse) {
        return gwjSceneExpendBusinessHouseMapper.selectGwjSceneExpendBusinessHouseList(gwjSceneExpendBusinessHouse);
    }

    /**
     * 新增业务房屋信息（旧支出模块）
     * 
     * @param gwjSceneExpendBusinessHouse 业务房屋信息（旧支出模块）
     * @return 结果
     */
    @Override
    public int insertGwjSceneExpendBusinessHouse(GwjSceneExpendBusinessHouse gwjSceneExpendBusinessHouse) {
        gwjSceneExpendBusinessHouse.setCreateTime(DateUtils.getNowDate());
        return gwjSceneExpendBusinessHouseMapper.insertGwjSceneExpendBusinessHouse(gwjSceneExpendBusinessHouse);
    }

    /**
     * 修改业务房屋信息（旧支出模块）
     * 
     * @param gwjSceneExpendBusinessHouse 业务房屋信息（旧支出模块）
     * @return 结果
     */
    @Override
    public int updateGwjSceneExpendBusinessHouse(GwjSceneExpendBusinessHouse gwjSceneExpendBusinessHouse) {
        gwjSceneExpendBusinessHouse.setUpdateTime(DateUtils.getNowDate());
        return gwjSceneExpendBusinessHouseMapper.updateGwjSceneExpendBusinessHouse(gwjSceneExpendBusinessHouse);
    }

    /**
     * 批量删除业务房屋信息（旧支出模块）
     * 
     * @param bizHouseIds 需要删除的业务房屋信息（旧支出模块）主键
     * @return 结果
     */
    @Override
    public int deleteGwjSceneExpendBusinessHouseByBizHouseIds(Long[] bizHouseIds) {
        return gwjSceneExpendBusinessHouseMapper.deleteGwjSceneExpendBusinessHouseByBizHouseIds(bizHouseIds);
    }

    /**
     * 删除业务房屋信息（旧支出模块）信息
     * 
     * @param bizHouseId 业务房屋信息（旧支出模块）主键
     * @return 结果
     */
    @Override
    public int deleteGwjSceneExpendBusinessHouseByBizHouseId(Long bizHouseId) {
        return gwjSceneExpendBusinessHouseMapper.deleteGwjSceneExpendBusinessHouseByBizHouseId(bizHouseId);
    }

    /* 
     * 修改房屋选中状态
     */
    @Override
    public int changeHouseIfSelected(Long bizId, String selectFlag, Long areaId, String[] houseCodes) {
        if (StringUtils.isNull(bizId) || StringUtils.isNull(selectFlag) || StringUtils.isNull(areaId) || StringUtils.isEmpty(houseCodes)) {
            throw new ServiceException("业务ID，选择状态，地区编号或房屋编号不能为空");
        }
        return gwjSceneExpendBusinessHouseMapper.changeHouseIfSelected(bizId, selectFlag, areaId, houseCodes);
    }

    /* 
     * 根据业务ID批量新增房屋信息
     */
    @Override
    public int insertBatchGwjSceneExpendBusinessHouseByBaseHouse(Long bizId, List<GwjBaseHouse> houseList) {
        return gwjSceneExpendBusinessHouseMapper.insertBatchGwjSceneExpendBusinessHouseByBaseHouse(bizId, houseList);
    }

    /* 
     * 根据业务ID删除房屋信息
     */
    @Override
    public int deleteGwjSceneExpendBusinessHouseByBizId(Long bizId) {
        return gwjSceneExpendBusinessHouseMapper.deleteGwjSceneExpendBusinessHouseByBizId(bizId);
    }

    /* 
     * 根据业务ID获取实际分摊金额统计数据
     */
    @Override
    public BigDecimal selectActualAllocationMoneyTotalBybizIdAndAreaId(Long bizId, Long areaId) {
        return gwjSceneExpendBusinessHouseMapper.selectActualAllocationMoneyTotalBybizIdAndAreaId(bizId, areaId);
    }

    /* 
     * 根据业务ID查询房屋类型
     */
    @Override
    public List<String> selectHouseUseType(Long bizId) {
        List<String> list = gwjSceneExpendBusinessHouseMapper.selectHouseUseType(bizId);
        list.add(0, "全部");
        return list;
    }

    /* 
     * 根据业务ID统计房屋数据
     */
    @Override
    public Map<String, BigDecimal> countHoustData(Long bizId, Long areaId, String selectFlag) {
        return gwjSceneExpendBusinessHouseMapper.countHoustData(bizId, selectFlag);
    }

    /**
     * 20230821
     * 
     * 根据业务ID批量修改房屋信息
     * 
     * @param bizId 业务ID
     * @param houseList 房屋列表
     * @return
     */
    @Override
    public int upBatchGwjSceneExpendBusinessHouseByBaseHouse(List<GwjSceneExpendBusinessHouse> houseList) {
        return gwjSceneExpendBusinessHouseMapper.upBatchGwjSceneExpendBusinessHouseByBaseHouse(houseList);
    }

    /**
     * 根据条件查询房屋数据
     * 
     * 20230821
     * 
     * hmh
     * 
     * @param bizId 业务ID
     * @param areaId 地区ID
     * @param selectFlag 选中状态
     * @return
     */
    @Override
    public List<GwjSceneExpendBusinessHouseAndOwner> selectGwjSceneExpendBusinessHousesAndOwners(Long bizId, Long areaId, String selectFlag) {
        return gwjSceneExpendBusinessHouseMapper.selectGwjSceneExpendBusinessHousesAndOwners(bizId, areaId, selectFlag);
    }

    /* 
     * 检查业主信息
     */
    @Override
    public boolean checkOwnerInfo(Long bizId) {
        // 目前只显示10条未正确输入业主信息记录
        List<LinkedHashMap<String, Object>> list = gwjSceneExpendBusinessHouseMapper.checkOwnerInfo(bizId);
        if (StringUtils.isNotEmpty(list)) {
            StringBuffer sb = new StringBuffer();
            list.stream().forEach(m -> {
                sb.append("房屋编号").append(m.get("houseCode")).append("：");
                String ownerNameMsg = StringUtils.isEmpty((String)m.get("ownerName")) ? "业主姓名为空！；" : "";
                sb.append(ownerNameMsg);
                String cardNumMsg = StringUtils.isEmpty((String)m.get("cardNum")) ? "业主身份证为空！；" : "";
                sb.append(cardNumMsg);
                String phoneMsg = StringUtils.isEmpty((String)m.get("phone")) ? "业主手机号为空！；" : "";
                sb.append(phoneMsg).append("\n");
            });
            throw new ServiceException("当前业务存在未处理业务信息: \n" + sb.toString());
        }
        return true;
    }

    /* 
     * 根据业务ID更改房屋和业主信息
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updatBusinessHouseAndOwnerInfoByBizId(GwjSceneExpendHouseAndOwnerRequest gsehaor) {
        if (gsehaor.getBizId() > 0 && StringUtils.isNotNull(gsehaor.getHouseCode())) {
            // 除非数据操作异常否则当成功！
            // 原始房屋数据
            // 获取房屋数据
            GwjSceneExpendBusinessHouse gsebh = gwjSceneExpendBusinessHouseMapper.selectGwjSceneExpendBusinessHouseByBizIdAndHouseCode(gsehaor.getBizId(), gsehaor.getHouseCode());
            // 已选中，非公用户进行修改
            if (!"1".equals(gsebh.getSelectFlag()) && !"0".equals(gsebh.getPublicFlag())) {
                throw new ServiceException("不允许修改未选中或者公用户房屋信息！");
            }
            // 获取操作人员信息
            SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
            // 因为前端调用该方法是使用单个字段上传，这里增加判断，减少操作
            upHouseInfo(gsebh, gsehaor, sysUser);
            upOwnerInfo(gsehaor, sysUser);
            return true;
        }
        return false;
    }

    /**
     * 业务逻辑参照com.yida.gwj.expend.outside.service.impl.GwjMaintenanceFundsBusinessServiceImpl下的shareEquallyMoneyUpdate方法
     * 后期问题再进行调整
     * 
     * 实际分摊金额=差额+应分摊金额
     * 
     * 本次分摊总金额=差额+应分摊金额+自筹金额
     * 
     * @param gwjHouseAndOwnerRequest
     */
    // @Transactional(rollbackFor = Exception.class)
    private void upHouseInfo(GwjSceneExpendBusinessHouse gsebh, GwjSceneExpendHouseAndOwnerRequest gsehaor, SysUser sysUser) {
        if (gsehaor.getLackMoney() == null && gsehaor.getSelfRaiseMoney() == null) {
            return;
        }
        // 业务ID
        Long bizId = gsehaor.getBizId();
        // 获取当前房屋数据

        // 获取当前房屋未修改前数据
        // 历史差额
        BigDecimal oldLackMoney = gsebh.getLackMoney();
        // 历史实际分摊金额
        BigDecimal allocationMoney = gsebh.getAllocationMoney();
        // 历史实际分摊金额
        BigDecimal oldActualAllocationMoney = gsebh.getActualAllocationMoney();
        // 历史自筹金额
        BigDecimal oldSelfRaiseMoney = gsebh.getSelfRaiseMoney();
        // 本次分摊总金额
        // BigDecimal oldTotalAllocationMoney = gmfbh.getTotalAllocationMoney();
        // 变动房屋数据
        // 差额
        BigDecimal requestLackMoney = gsehaor.getLackMoney();
        // BigDecimal changeLackMoney = StringUtils.isNull(requestLackMoney) ? new BigDecimal(0) : requestLackMoney;
        BigDecimal changeLackMoney = StringUtils.isNull(requestLackMoney) ? oldLackMoney : requestLackMoney;
        // 自筹金额
        BigDecimal requestSelfRaiseMoney = gsehaor.getSelfRaiseMoney();
        // BigDecimal changeSelfRaiseMoney = StringUtils.isNull(requestSelfRaiseMoney) ? new BigDecimal(0) :
        // requestSelfRaiseMoney;
        BigDecimal changeSelfRaiseMoney = StringUtils.isNull(requestSelfRaiseMoney) ? oldSelfRaiseMoney : requestSelfRaiseMoney;
        // 当前变动的实际分摊金额(历史实际分摊金额-历史差额+变动差额)
        BigDecimal changeActualAllocationMoney = allocationMoney.add(changeLackMoney);
        // 当前变动本次分摊总金额(变更后的实际分摊金额+变更自筹金额)
        BigDecimal changeTotalAllocationMoney = allocationMoney.add(changeLackMoney).add(changeSelfRaiseMoney);
        // 注：精度缺失情况下，考虑保留两位小数
        // 更新当前房屋数据
        gwjSceneExpendBusinessHouseMapper.updateGwjSceneExpendBusinessHouseByHouseCodeAndBizId(new GwjSceneExpendBusinessHouse() {
            /**
             *
             */
            private static final long serialVersionUID = 4019494863942169353L;
            {
                // 业务ID
                setBizId(bizId);
                // 房屋标识码
                setHouseCode(gsehaor.getHouseCode());
                // 差额
                setLackMoney(requestLackMoney);// 改换请求参数，避免转换为0时重置了结果
                // 自筹金额
                setSelfRaiseMoney(requestSelfRaiseMoney);
                // 实际分摊金额
                setActualAllocationMoney(changeActualAllocationMoney);
                // 本次分摊总金额
                setTotalAllocationMoney(changeTotalAllocationMoney);
                // 更新人
                setUpdateBy(sysUser.getRealName());
                // 更新时间
                setUpdateTime(DateUtils.getNowDate());
            }
        });
        // // 更新当前业务数据
        // // 获取当前业务金额统计数据
        // Map<String, BigDecimal> countMoneyMap = gwjSceneExpendBusinessHouseMapper.countHoustData(bizId, "1");
        // // 获取总差额
        // // countMoneyMap.get("total_lack_money");
        // // 获取总实际分摊金额
        // BigDecimal total_actual_allocation_money = countMoneyMap.get("total_actual_allocation_money");
        // // total_actual_allocation_money = total_actual_allocation_money.subtract(oldLackMoney).add(changeLackMoney);
        // // 获取总自筹金额
        // // countMoneyMap.get("total_self_raise_money");
        // // 获取总分摊总金额
        // BigDecimal total_total_allocation_money = countMoneyMap.get("total_total_allocation_money");
        // // 总得实际分摊金额+变动自筹金额
        // // BigDecimal total_total_allocation_money = total_actual_allocation_money.add(changeSelfRaiseMoney);
        // gwjMaintenanceFundsBusinessInfoService.updateGwjMaintenanceFundsBusinessInfo(new
        // GwjMaintenanceFundsBusinessInfo() {
        // {
        // setBizId(gwjHouseAndOwnerRequest.getBizId());
        // setActualAllocationAmount(total_actual_allocation_money);
        // setTotalAllocatedSettlementAmount(total_total_allocation_money);
        // }
        // });
    }

    private void upOwnerInfo(GwjSceneExpendHouseAndOwnerRequest gsehaor, SysUser sysUser) {
        // 三个值都为空不进行调用操作
        if (StringUtils.isNull(gsehaor.getOwnerName()) && StringUtils.isNull(gsehaor.getPhone()) && StringUtils.isNull(gsehaor.getCardNum())) {
            return;
        }
        // 待操作数据
        GwjSceneExpendBusinessOwner opGwjMaintenanceFundsBusinessOwner = new GwjSceneExpendBusinessOwner() {
            /**
            *
            */
            private static final long serialVersionUID = -2988855505227945676L;

            {
                // 业务ID
                setBizId(gsehaor.getBizId());
                // 房屋标识码
                setHouseCode(gsehaor.getHouseCode());
                // 名称
                setOwnerName(gsehaor.getOwnerName());
                // 手机号
                setOwnerPhone(gsehaor.getPhone());
                // 身份证号
                setCardNum(gsehaor.getCardNum());
                // 更新人
                setUpdateBy(sysUser.getRealName());
                // 更新时间
                setUpdateTime(DateUtils.getNowDate());
            }
        };
        GwjSceneExpendBusinessOwner rGwjSceneExpendBusinessOwner = iGwjSceneExpendBusinessOwnerService.selectGwjSceneExpendBusinessOwnerByBizIdAndHouseCode(gsehaor.getBizId(), gsehaor.getHouseCode());
        if (StringUtils.isNull(rGwjSceneExpendBusinessOwner)) {
            // 空进行新增
            iGwjSceneExpendBusinessOwnerService.insertGwjSceneExpendBusinessOwner(opGwjMaintenanceFundsBusinessOwner);
            return;
        }
        // 否则进行修改
        iGwjSceneExpendBusinessOwnerService.updateGwjSceneExpendBusinessOwnerByBizIdAndHouseCode(opGwjMaintenanceFundsBusinessOwner);
    }

    /**
     * 根据业务ID和房屋标识码查询业务房屋
     */
    @Override
    public GwjSceneExpendBusinessHouse selectGwjSceneExpendBusinessHouseByBizIdAndHouseCode(Long bizId, String houseCode) {
        return gwjSceneExpendBusinessHouseMapper.selectGwjSceneExpendBusinessHouseByBizIdAndHouseCode(bizId, houseCode);
    }
}
